const express = require('express');
const router = express.Router();
const Project = require('../models/project.model');
const projectController = require('../controllers/project.controller');
const { auth } = require('../middleware/auth.middleware');

// 获取所有项目
router.get('/', auth, async (req, res) => {
  try {
    console.log('Fetching projects...');
    
    // 获取所有项目的部署日志统计
    const projects = await Project.aggregate([
      {
        $lookup: {
          from: 'deploylogs',  // DeployLog 集合名
          localField: '_id',
          foreignField: 'projectId',
          as: 'deployLogs'
        }
      },
      {
        $addFields: {
          deployStats: {
            totalCount: { $size: '$deployLogs' },
            successCount: {
              $size: {
                $filter: {
                  input: '$deployLogs',
                  as: 'log',
                  cond: { $eq: ['$$log.status', 'success'] }
                }
              }
            }
          }
        }
      },
      {
        $project: {
          deployLogs: 0  // 移除deployLogs数组,只保留统计结果
        }
      }
    ]);

    console.log('Found projects:', projects.length);
    res.json(projects);
  } catch (error) {
    console.error('Error fetching projects:', error);
    res.status(500).json({ 
      error: '获取项目列表失败',
      message: error.message,
      stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
    });
  }
});

// 创建新项目
router.post('/', auth, async (req, res) => {
  try {
    const project = new Project(req.body);
    await project.save();
    res.status(201).json(project);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取单个项目
router.get('/:id', auth, async (req, res) => {
  try {
    const project = await Project.findById(req.params.id);
    if (!project) {
      return res.status(404).json({ error: '项目不存在' });
    }
    res.json(project);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 更新项目
router.put('/:id', auth, async (req, res) => {
  try {
    const project = await Project.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    );
    if (!project) {
      return res.status(404).json({ error: '项目不存在' });
    }
    res.json(project);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 删除项目
router.delete('/:id', auth, async (req, res) => {
  try {
    const project = await Project.findByIdAndDelete(req.params.id);
    if (!project) {
      return res.status(404).json({ error: '项目不存在' });
    }
    res.json({ message: '项目已删除' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 测试服务器连接
router.post('/test-connection', auth, projectController.testServerConnection);

module.exports = router; 